import celery
from celery import Celery
from ecelery.globa_vars import auto_register_celery_tasks


class Emtpy:
    pass


def easy_start_worker(app, broker=None, result_backend=None, loglevel='info', concurrency=4, pool=None, autoscale=None, no_color=False,
                      quiet=False, hostname=None, detach=False, statedb=None, prefetch_multiplier=None, events=True, time_limit=None,
                      soft_time_limit=None, max_tasks_per_child=None, max_memory_per_child=None, queues=None, exclude_queues=None, include=None,
                      logfile=None, pidfile=None, function_tasks=None, **other_args
                      ):
    """
    脚本直接启动celery，而非命令行

    prefork (default), eventlet,gevent or solo,
    :return:
    """
    auto_register_celery_tasks()
    if function_tasks:
        if queues:
            raise ValueError('设置了 function_tasks 时候不需要设置queues')
        function_task_queues = [task.name for task in function_tasks]
        queues = ','.join(function_task_queues)
    argv = ['worker', f'--pool={pool}' if pool else Emtpy, f'--concurrency={concurrency}', f'--hostname={hostname}' if hostname else Emtpy,
            f'--loglevel={loglevel}',
            f'--queues={queues}' if queues else Emtpy, '--detach' if detach else Emtpy, f'--autoscale={autoscale}' if autoscale else Emtpy,
            f'--no-color' if no_color else Emtpy,
            ]
    argv = [item for item in argv if item != Emtpy]
    print(f'celery 启动命令是 :  {argv}')
    app.worker_main(argv=argv)
